package org.carpediem.conman.dao;

import org.carpediem.conman.entity.Contact;
import org.carpediem.conman.entity.Document;
import org.carpediem.schema.conman.ContactInfo;
import org.carpediem.schema.conman.DocumentInfo;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Mark Petrovic
 */
public class DocumentDaoImpl extends DocumentDao {
   /* private HibernateTemplate hibernateTemplate;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }*/

    public Document get(long documentId) {
        Document document = (Document) hibernateTemplate.get(Document.class, documentId);
        return document;
    }

    public List<Document> getAllDocuments() {
        return hibernateTemplate.loadAll(Document.class);
    }

    public List<Document> getByOwner(final Contact contact) {
        return (List<Document>) hibernateTemplate.execute(new ByOwner(contact));
    }

    public Document add(Contact contact, ContactInfo cInfo, byte[] docBuffer) {
        // Todo:  index bounds check
        DocumentInfo dInfo = cInfo.getContact().getDocumentInfo().get(0);

        Document document = new Document();
        document.setOriginalName(dInfo.getOriginalName());
        document.setMimeType(dInfo.getMimetype());
        document.setBuffer(docBuffer);
        document.setUri(getS3Persister().documentUri(docBuffer));
        contact.addDocument(document);

        hibernateTemplate.saveOrUpdate(document);

        cacheLocally(contact);
        index(contact);

        getS3Persister().enqueue(contact);

        return document;
    }

    private class ByOwner implements HibernateCallback {
        private Contact contact;

        public ByOwner(Contact contact) {
            this.contact = contact;
        }

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createQuery("from Document where contact =:aContact");
            query.setParameter("aContact", contact);
            return query.list();
        }
    }
}
